package vip.aster.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.aster.system.entity.SysUserPost;
import vip.aster.system.mapper.SysUserPostMapper;
import vip.aster.system.service.SysUserPostService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户岗位关系 服务实现类
 * </p>
 *
 * @author Aster
 * @since 2023-11-28 10:36
 */
@Service
@AllArgsConstructor
public class SysUserPostServiceImpl extends ServiceImpl<SysUserPostMapper, SysUserPost> implements SysUserPostService {
    @Override
    public List<String> getPostIdList(String userId) {
        LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPost::getUserId, userId);
        List<SysUserPost> list = this.list(queryWrapper);
        return CollUtil.isEmpty(list) ? ListUtil.empty() : list.stream().map(SysUserPost::getPostId).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePostList(String userId, List<String> postIds) {
        List<SysUserPost> list = postIds.stream().map(postId -> {
            SysUserPost userPost = new SysUserPost();
            userPost.setUserId(userId);
            userPost.setPostId(postId);
            return userPost;
        }).toList();

        // 先删除再新增
        LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserPost::getUserId, userId);
        this.remove(queryWrapper);

        // 批量保存
        this.saveBatch(list);
    }

    @Override
    public void deleteByUserIdList(List<String> userIds) {
        LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysUserPost::getUserId, userIds);
        this.remove(queryWrapper);
    }
}
